package com.module.login;

import java.math.BigInteger;
import java.security.MessageDigest;

import org.phprpc.util.PHPSerializer;
import org.xsocket.connection.INonBlockingConnection;

import com.command.Group;
import com.connect.agreement.Packet;
import com.game.database.MysqlHelper;
import com.server.ServerSimulation;
import com.server.User;

public class LoginManager {
	public static final byte LoginNormal = 1;
	public static final byte IsLogin = 2;
	public static final byte LogoutNormal = 3;
	public static final byte LoginSuccess = 4;
	public static final byte LoginFailed = 5;

	public static User login(String account, String passwd){
		boolean ispasswd = checkPasswd(account, passwd);
		if(ispasswd){
			User user = User.getUser(account);
			if(user==null){
				user = User.createUser(account);
			}
			user.ctrl = 1;
			user.updateAttribute("ctrl");
			return user;
		}
		else
		{
			return null;
		}
	}
	public static void logout(User user){
		user.ctrl = 0;
		user.updateAttribute("ctrl");
	}
	
	public static boolean checkPasswd(String account,String passwd){
		Object[] parms = new Object[1];
		parms[0] = account;
		try {
			Object pass = MysqlHelper.ExecuteScalar("select passwd from sys_account_check where account = ?", parms);
			if(pass==null||passwd==null){
				return ServerSimulation.isDev;
			}
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(passwd.getBytes());
			String pwd = new BigInteger(1, md.digest()).toString(16);
			return pwd.equals(pass);
		} catch (Exception e) {
			e.printStackTrace();
			return ServerSimulation.isDev;
		}
	}
	
	public static void update(INonBlockingConnection nbc,Packet packet){
		if(packet == null)
			return;
		try {
			Packet returnpacket = null;
			switch(packet.getCmd()){
			case LoginNormal://正常登录
				PHPSerializer  p = new PHPSerializer();
				Login loginobj = (Login) p.unserialize(packet.getContent(), Login.class);
				User user = login(loginobj.account, loginobj.passwd);
				returnpacket = new Packet();
				if(user!=null){
					ServerSimulation.get().attachUser(user,nbc);
					returnpacket.setBuffer(Group.Login, LoginSuccess, new PHPSerializer().serialize(user),true);
				} else {
					returnpacket.setBuffer(Group.Login, LoginFailed, (byte[])null,true);
				}
				break;
			case LogoutNormal:
				
				break;
			}
			if(returnpacket!=null)
				nbc.write(returnpacket.byteBuffer());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
